package cn.tedu.store.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.District;
import cn.tedu.store.mapper.AddressMapper;
import cn.tedu.store.mapper.DistrictMapper;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.service.IDistrictService;
import cn.tedu.store.service.ex.AccessDeniedException;
import cn.tedu.store.service.ex.AdderssNotFoundException;
import cn.tedu.store.service.ex.AddressCountLimitException;
import cn.tedu.store.service.ex.DeleteException;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.service.ex.UpdateException;

@Service
public class AddressServiceImpl implements IAddressService {

	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private IDistrictService districtService;
	@Override
	public void addnew(Address address, Integer uid, String username)
			throws AddressCountLimitException, InsertException {
		//根据参数uid，查询收货地址的数量
		int count=addressMapper.coundByUid(uid);
        //如果收货地址数量大于ADDRESS_MAX_COUNT,抛出AddressCountLimitException
		if (count>=ADDRESS_MAX_COUNT) {
			throw new AddressCountLimitException("收货地址超过"+ADDRESS_MAX_COUNT+"个,不能添加！");
		}
        //补全uid
		address.setUid(uid);
        //根据省市区code补全相应名称
		District province= districtService.getByCode(address.getProvince_code());
		District city= districtService.getByCode(address.getCity_code());
		District area= districtService.getByCode(address.getArea_code());
		if (province==null) {
			address.setProvince_code(null);
		}else {
			address.setProvince_name(province.getName());
		}
		if (city==null) {
			address.setCity_code(null);
		}else {
			address.setCity_name(city.getName());
		}
		if (area==null) {
			address.setArea_code(null);
		}else {
			address.setArea_name(area.getName());
		}
		
        //判断收货地址是否为0，是则设置is_default=1
		if(count==0) {
			address.setIs_default(1);
		}
		else {
			address.setIs_default(0);
		}
        //创建当前时间对象
		Date now=new Date();
        //补全实体基类数据（日志），比如created_user
		address.setCreated_time(now);
		address.setModified_time(now);
		address.setCreated_user(username);
		address.setModified_user(username);
        //插入地址数据
		addressMapper.insert(address);

	}
	@Override
	public List<Address> getByUid(Integer uid) {
		
		return findByUid(uid);
	}
	
	private List<Address> findByUid(Integer uid){
	    return addressMapper.findByUid(uid);
	}

	private void updateNonDefault(Integer uid) throws UpdateException{
		Integer rows=addressMapper. updateNonDefault(uid);
		if (rows==0){
		    throw new UpdateException("数据修改未知异常");
		}
		
	}

	private void updateDefault(Integer aid,String modified_user,Date modified_time) throws UpdateException{
		Integer rows=addressMapper.updateDefault(aid,modified_user,modified_time);
		if (rows!=1){
		    throw new UpdateException("数据修改未知异常");
		}
	}

	private Address findByAid(Integer aid) {
				
		return addressMapper.findByAid(aid);
	}
	@Override
	@Transactional
	public void setDefault(Integer aid, Integer uid, String username)
			throws AdderssNotFoundException, AccessDeniedException, UpdateException {
		//根据aid查询收货地址
		Address result=findByAid(aid);
	    //判断是否为null
		
	    //是，throw new  AdderssNotFoundException
		if (result==null) {
			throw new AdderssNotFoundException("收货地址未找到");
		}
	    //判断查询结果中的uid与参数uid是否一致
	    //不是，throw new  AccessDeniedException
		if(result.getUid()!=uid) {
			throw new  AccessDeniedException("不能修改非本人地址数据");
		}
	    //将所有设为非默认
		addressMapper.updateNonDefault(uid);
	    //将指定设为默认
		addressMapper.updateDefault(aid, username, new Date());
	}
	
	@Override
	@Transactional
	public void delete(Integer aid, Integer uid, String username)
			throws AdderssNotFoundException, AccessDeniedException, DeleteException, UpdateException {
		//根据aid查询收货地址
		Address result=findByAid(aid);
	    //判断是否为null				
	   //是，throw new  AdderssNotFoundException
		if (result==null) {
			throw new AdderssNotFoundException("收货地址未找到");
		}
		//判断查询结果中的uid与参数uid是否一致
		//不是，throw new  AccessDeniedException
			if(result.getUid()!=uid) {
				throw new  AccessDeniedException("不能修改非本人地址数据");
			}
		//执行删除
			deleteByAid(aid);
		//判断此前查询的is_default 是否为0
			if (result.getIs_default()==0) {
		       return;
			}
     
		//统计当前用户收货地址数量
			int count=addressMapper.coundByUid(uid);
		//判断剩余数量是否为0
			if(count==0) {
				return;
			}
  
		//查询最近修改的收货地址
			Address lastAddress=findLastModified(uid);
		//将最近修改的设为默认
			updateDefault(lastAddress.getAid(), username, new Date());
	}
	
	private void deleteByAid(Integer aid) throws DeleteException{
	    Integer rows=addressMapper.deleteByAid(aid);
	    if(rows!=1) {
	    	throw new DeleteException("删除错误");
	    }
	}
	private Address findLastModified(Integer uid){
	    return addressMapper.findLastModified(uid);
	}
	@Override
	public Address getByAid(Integer aid) {
		
		return addressMapper.findByAid(aid);
	}
	
	
}
